#!/usr/bin/env python
import os
from waf_dynamo import platform_supports_feature, platform_glfw_version
from BuildUtility import create_build_utility
from waflib import Options

def _get_native_file(target_os, name):
    native_source = '%s/%s' % (target_os, name)
    if not os.path.exists(os.path.join('..','src',native_source)):
        native_source = name
    return native_source

def build(bld):
    build_util = create_build_utility(bld.env)

    platform_folder = _get_native_file(build_util.get_target_os(), '../glfw')

    obj = bld.program(features = 'cxx test',
                      includes = ['../%s' % build_util.get_target_os(), '..', '.', platform_folder],
                      use      = 'TESTMAIN DLIB PROFILE_NULL DMGLFW SOCKET PLATFORM_NULL hid_null',
                      target   = 'test_hid',
                      source   = 'test_hid.cpp')

    platform_lib = []
    graphics_lib = []
    graphics_lib_symbols = []

    if platform_supports_feature(bld.env.PLATFORM, 'opengles', {}):
        platform_lib = ['PLATFORM']
        graphics_lib = ['GRAPHICS_OPENGLES', 'DMGLFW']
        graphics_lib += ['OPENGLES']
        graphics_lib_symbols += ['GraphicsAdapterOpenGLES']
    elif platform_supports_feature(bld.env.PLATFORM, 'opengl', {}):
        platform_lib = ['PLATFORM']
        graphics_lib = ['GRAPHICS', 'DMGLFW']
        graphics_lib += ['OPENGL']
        graphics_lib_symbols += ['GraphicsAdapterOpenGL']

    if platform_supports_feature(bld.env.PLATFORM, 'vulkan', {}) and Options.options.with_vulkan:
        graphics_lib_symbols += ['GraphicsAdapterVulkan']
        graphics_lib += ['GRAPHICS_VULKAN', 'VULKAN']
        if platform_glfw_version(bld.env.PLATFORM) == 3:
            platform_lib = ['PLATFORM_VULKAN']

    if len(graphics_lib_symbols) == 0:
        graphics_lib = ['GRAPHICS_NULL']
        graphics_lib_symbols = ['GraphicsAdapterNull']
        platform_lib = ['PLATFORM_NULL']

    if bld.env.PLATFORM in ('arm64-nx64') and 'DMGLFW' in graphics_lib:
        graphics_lib.remove('DMGLFW')

    glfw_js = '%s/ext/lib/%s/js/library_glfw.js' % (bld.env.DYNAMO_HOME, bld.env.PLATFORM)

    web_libs = [glfw_js, 'library_sys.js']

    bld.program(features = 'cxx test skip_test',
        includes = ['../%s' % build_util.get_target_os(), '..', '.', platform_folder],
        use = 'TESTMAIN APP DLIB DINPUT PROFILE_NULL SOCKET HID hid'.split() + platform_lib + graphics_lib,
        web_libs = web_libs,
        exported_symbols = graphics_lib_symbols,
        target = 'test_app_hid',
        source = 'test_app_hid.cpp')
